import { createStore } from 'vuex'
//登录
import { Login } from '../api/loginPage'
// vuex持久化
import createPersistedState from 'vuex-persistedstate'
//存取Cokkie
import Cookie from 'js-cookie'
//组件库的message
import { message } from 'ant-design-vue'

export default createStore({
  state: {
    //存储用户信息
    user: {}
  },
  getters: {},
  mutations: {
    //设置state
    set_state(state, data: any) {
      // state[data.key] = data.data
    }
  },
  actions: {
    //登录
    async Login({ commit, dispatch }, payload) {
      //登录
      const res = await Login(payload)
      if (res.data.status === 200) {
        //成功提示
        message.success(res.data.message)
        //存储token
        Cookie.set('token', res.data.token)
        //获取动态路由表
        dispatch('getRouters', res.data.user.role)
        //通过角色获取动态路由
        // filterRouter(routers, res.data.user.role).forEach((item) => {
        //   router.addRoute(item)
        // })
        //存储用户信息
        commit('set_state', { key: 'user', data: res.data.user })
      } else {
        //失败提示
        message.error(res.data.message)
      }
    }
  },
  modules: {},
  plugins: [
    createPersistedState({
      storage: window.sessionStorage,
      reducer(state: { user: any }) {
        return {
          // 只储存state中的user
          user: state.user
        }
      }
    })
  ]
})
